using System.Threading.Tasks;
using JT.WEB.Areas.Identity.Data;
using JTWEB3.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace JT.WEB.Controllers
{
    [Authorize(Policy = "仅限管理员")]
    // [Authorize( = "Administrators")]
    public class RoleController : Controller
    {
        public RoleManager<IdentityRole> RoleManager { get; }
        public UserManager<JTWEB3User> UserManager { get; }

        public RoleController(RoleManager<IdentityRole> roleManager, UserManager<JTWEB3User> userManager)
        {
            RoleManager = roleManager;
            UserManager = userManager;
        }
        // GET: Role
        public async Task<ActionResult> Index()
        {
            System.Collections.Generic.List<IdentityRole> roles = await RoleManager.Roles.ToListAsync().ConfigureAwait(false);
            if (roles == null)
            {
                return View();
            }
            return View(roles);
        }

        // GET: Role/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Role/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(IdentityRole role)
        {
            try
            {
                // TODO: Add insert logic here
                if (role.Name == null)
                {
                    return View();
                }

                IdentityResult result = await RoleManager.CreateAsync(role);
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: Role/Edit/5
        public ActionResult Edit()
        {
            return View();
        }

        // POST: Role/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, IFormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: Role/Delete/5
        //public ActionResult Delete()
        //{
        //    return View("Index");
        //}

        //POST: Role/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Delete(string id)
        {
            if (id == null)
            {
                ModelState.AddModelError(string.Empty, "删除失败");

            }
            else
            {
                // TODO: Add delete logic here
                IdentityRole role = await RoleManager.FindByIdAsync(id);
                IdentityResult result = await RoleManager.DeleteAsync(role);
                if (!result.Succeeded)
                {
                    foreach (IdentityError item in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, item.Description);
                    }

                }

            }
            return RedirectToAction(nameof(Index));

        }

        [HttpGet]
        public async Task<IActionResult> AddUser(string id)
        {
            IdentityRole role = await RoleManager.FindByIdAsync(id);
            System.Collections.Generic.List<JTWEB3User> users = await UserManager.Users.ToListAsync();
            Roles m_role = new Roles
            {
                RoleId = role.Id,
                RoleName = role.Name
            };
            foreach (JTWEB3User i in users)
            {
                if (!await UserManager.IsInRoleAsync(i, role.Name))
                {
                    m_role.UserList.Add(i);
                }
            }
            return View(m_role);
        }

        [HttpPost]
        public async Task<IActionResult> AddUser(Roles myRole)
        {
            if (myRole is null)
            {
                throw new System.ArgumentNullException(nameof(myRole));
            }

            if (myRole.UserId != null)
            {
                JTWEB3User user = await UserManager.FindByIdAsync(myRole.UserId).ConfigureAwait(false);
                if (user != null)
                {

                    IdentityResult result = await UserManager.AddToRoleAsync(user, myRole.RoleName).ConfigureAwait(false);
                    if (result.Succeeded)
                    {
                        return RedirectToAction(nameof(Detail), new { id = myRole.RoleId });
                    }
                    foreach (IdentityError i in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, i.Description);
                    }

                }
            }
            ModelState.AddModelError(string.Empty, "用户名不能为空");
            return View();

        }

        [HttpPost]
        public async Task<IActionResult> DeleteUser(Roles m_role)
        {
            if (m_role != null)
            {
                JTWEB3User user = await UserManager.FindByIdAsync(m_role.UserId);
                if (user != null)
                {

                    IdentityResult result = await UserManager.RemoveFromRoleAsync(user, m_role.RoleName);
                    if (result.Succeeded)
                    {
                        return RedirectToAction(nameof(Detail), new { id = m_role.RoleId });
                    }
                    foreach (IdentityError i in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, i.Description);
                    }

                }
            }
            ModelState.AddModelError(string.Empty, "用户名不能为空");
            return View();

        }
        public async Task<IActionResult> Detail(string id)
        {
            IdentityRole role = await RoleManager.FindByIdAsync(id);
            System.Collections.Generic.List<JTWEB3User> users = await UserManager.Users.ToListAsync();
            Roles vm = new Roles
            {
                RoleId = role.Id,
                RoleName = role.Name
            };
            foreach (JTWEB3User i in users)
            {
                if (await UserManager.IsInRoleAsync(i, role.Name))
                {
                    vm.UserList.Add(i);
                }
            }

            return View(vm);
        }
        //public async Task<IActionResult> Detail(string Id)
        //{
        //    var user = await UserManager.FindByIdAsync(Id);
        //    if (user!=null)
        //    {
        //        await UserManager.AddToRoleAsync(user, Id);
        //    }
        //    return View();
        //}

    }
}